import { callWithNuxt } from '#app'
import {FetchContext, FetchResponse} from 'ofetch'
import {TOKEN_NAME,USER_INFO,SUCCESS_CODE,TOKEN_EXPIRE_CODE} from '~/common/constants'
import {getLangCommonData} from "~/utils/language";

export interface HttpRequest {
  headers?: Record<string, string>
  [key: string]: any
}

export interface HttpResponse<T = any> {
  code: string
  msg: string
  data: T
}


const getBaseUrl = () => {
  let baseURL = ''
  if (process.env.NODE_ENV === 'production') {
    //生产环境
    if (process.server) {
      //SSR请求内网
      baseURL = 'http://127.0.0.1:8080/api'
    }else {
      baseURL = 'http://124.222.10.251:8080/api'
    }
  } else {
    //本地开发环境
    baseURL = 'http://124.222.10.251:8080/api'
  }
  return baseURL
}

export default (url: string, opt: HttpRequest) => {
  const token = useCookie(TOKEN_NAME)
  const tokenVal = token.value
  //添加请求头和token
  opt.headers = {
    ...opt.headers,
    ...(tokenVal ? {[TOKEN_NAME]: tokenVal} : {})
  }
  if(process.client) {
    if (localStorage.getItem(USER_INFO) && !tokenVal) {
      // token 过期
      localStorage.removeItem(USER_INFO)
      // useRouter().push({ path: "/" });
      navigateTo('/')
      const warnTokenText = getLangCommonData('tokenExpire')
      return Promise.reject(new Error(warnTokenText))
    }
  }
  const nuxtApp = useNuxtApp()
  return useFetch(url, {
    ...opt,
    baseURL: getBaseUrl(),
    async onResponse(context: FetchContext & { response: FetchResponse<HttpResponse> }): Promise<void> | void {
      const { response} = context
      const {code, msg, data} = response._data
      if (code === TOKEN_EXPIRE_CODE) {
        // token 过期
        if (tokenVal) token.value = null // deleteCookie
        if (process.client) {
          localStorage.removeItem(USER_INFO)
        }
        // 服务端处理跳转报错，交到前端页面处理了 nuxtApp.$request
        // await navigateTo('/') // , { replace: true }
        // callWithNuxt(nuxtApp, navigateTo, [
        //   "/",
        //   {replace: true}
        // ])
      }
    }
    // onRequest({ request, options }) {
    //   // 设置请求头
    //   options.headers = options.headers || {}
    //   options.headers.authorization = '...'
    // },
    // onResponse(context: FetchContext & { response: FetchResponse<HttpResponse> }): Promise<void> | void {
    //   const { response} = context
    //   const statusCode = response.status
    //   const {code: businessStatusCode, msg, traceId} = response._data
    //   console.log('--')
    //   console.log(statusCode)
    //   console.log(businessStatusCode)
    //   console.log(nuxtApp.$myPlugin('Jack'))
    //   nuxtApp.$notification()
    //   if (statusCode !== 200 || businessStatusCode !== '200') {
    //     // 请求失败弹出错误提示
    //     if (businessStatusCode.startsWith('E')) {
    //       // nuxtApp.$notification.error(`${msg} [${traceId}]`)
    //     } else {
    //       // nuxtApp.$notification.warn(`${msg} [${traceId}]`)
    //     }
    //   }
    // },
    // onResponseError(context: FetchContext & { response: FetchResponse<HttpResponse> }): Promise<void> | void {
    // }
  })
}
